<template>
    <div class="work-order">
        <!-- 我的工单 -->
        <van-tabs v-model:active="active" title-inactive-color="#a5a4a4" @click-tab="tabClick">
            <van-tab v-for="item in tabData" :key="item.title" :title="item.title" :name="item.type"></van-tab>
        </van-tabs>

        <!-- tab -->
        <div class="work-order-btn">
            <van-tabs v-model:active="btnActive" title-inactive-color="#a5a4a4" @click-tab="tabClick">
                <van-tab v-for="item in btnList" :key="item.value" :title="item.label" :name="item.value"></van-tab>
            </van-tabs>
        </div>

        <!-- 列表 -->
        <div class="card-list">
            <PaginationList v-slot="{ dataList }" :request-data="requestData" :bottom-position="1" ref="listRef">
                <WorkOrderListItem v-for="item in dataList" :key="item.ticket_number" :items="item" class="card-item"
                    @click="goDetail(item.ticket_number)">
                </WorkOrderListItem>
            </PaginationList>
        </div>

        <!-- 不再使用内联按钮，完全使用动态创建的按钮 -->
    </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { Result } from '@/utils/request'
import { useUserStore } from '@/stores/user'
import { getWorkOrderList } from '@/api/worksheets'
import PaginationList from '@/components/PaginationList.vue'
import WorkOrderListItem from './components/WorkOrderListItem.vue'
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
    tabClick()
    adjustBottomPadding()
    // 动态创建按钮
    createDynamicButton()
    adjustBottomPadding()
})
// 组件卸载时清理动态创建的按钮
onUnmounted(() => {
    // 移除按钮
    const btn = document.getElementById('create-order-btn-backup')
    if (btn && btn.parentNode) {
        btn.parentNode.removeChild(btn)
    }

    // 移除路由守卫
    if (routeGuard) {
        router.beforeEach(routeGuard)
        routeGuard = null
    }
})

// 路由变化监听函数
let routeGuard: any = null

// 创建动态按钮的函数
const createDynamicButton = () => {
    setTimeout(() => {
        // 确保只在工单列表页创建按钮
        const currentPath = window.location.href
        if (currentPath.includes('/worksheets') || currentPath.includes('/work-order')) {
            if (!document.getElementById('create-order-btn-backup')) {
                // 判断是否是Safari浏览器
                const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

                // 创建按钮
                const createBtn = document.createElement('div')
                createBtn.id = 'create-order-btn-backup'
                createBtn.innerHTML = '<span style="margin: 0 5px;">+</span><span style="margin: 0 5px;">创建新工单</span><span style="margin: 0 5px;">+</span>'

                // 基本样式
                let buttonStyles = `
                    position: fixed !important;
                    bottom: 0 !important;
                    left: 50% !important;
                    transform: translateX(-50%) !important;
                    width: 320px !important;
                    height: 45px !important;
                    background-color: #000 !important;
                    border-top-left-radius: 20px !important;
                    border-top-right-radius: 20px !important;
                    display: flex !important;
                    justify-content: center !important;
                    align-items: center !important;
                    color: white !important;
                    font-weight: bold !important;
                    z-index: 1 !important;
                    visibility: visible !important;
                    opacity: 1 !important;
                `;

                // Safari特定样式
                if (isSafari) {
                    // 将样式重置为具体像素值
                    buttonStyles = `
                        position: fixed !important;
                        bottom: 0 !important;
                        left: 0 !important;
                        right: 0 !important;
                        margin-left: auto !important;
                        margin-right: auto !important;
                        width: 390px !important;
                        height: 53px !important;
                        background-color: #000 !important;
                        border-top-left-radius: 20px !important;
                        border-top-right-radius: 20px !important;
                        display: flex !important;
                        justify-content: center !important;
                        align-items: center !important;
                        color: white !important;
                        font-weight: bold !important;
                        z-index: 1 !important;
                        visibility: visible !important;
                        opacity: 1 !important;
                    `;
                }

                createBtn.style.cssText = buttonStyles;
                createBtn.onclick = () => createWorkOrder();

                // 将按钮添加到body
                document.body.appendChild(createBtn);

                // 仅在未注册路由守卫时注册
                if (!routeGuard) {
                    routeGuard = router.beforeEach((to, from, next) => {
                        if (to.path !== '/worksheets' && to.path !== '/work-order') {
                            const btn = document.getElementById('create-order-btn-backup');
                            if (btn && btn.parentNode) {
                                btn.parentNode.removeChild(btn);
                            }
                        }
                        next();
                    });
                }
            }
        }
    }, 300);
};
const visible = computed(() => {
    return Number(localStorage.getItem('mobile_department'))
})

const router = useRouter()

const store = useUserStore()

const active = ref('ower')

const btnActive = ref(6)

const tabData = ref([
    {
        title: '我的工单',
        type: 'ower'
    },
    {
        title: '全部工单',
        type: 'all'
    }
])

const btnList = ref([
    {
        label: '全部',
        value: 6
    },
    {
        label: '创建工单',
        value: 0
    },
    {
        label: '待分配',
        value: 1
    },
    {
        label: '处理中',
        value: 2
    },
    {
        label: '对策审批中',
        value: 3
    },
    {
        label: '客户确认中',
        value: 4
    },
    {
        label: '关闭',
        value: 5
    }
])

const listRef = ref<InstanceType<typeof PaginationList>>()

// 获取列表数据
const requestItems = (activeValue: string, btnActiveValue: number, pageIndex: number, pageSize: number): Promise<Result> => {
    return new Promise((resolve, reject) => {
        const params = {
            page: pageIndex,
            pageSize: pageSize,
            category: activeValue,
            ticket_state: btnActiveValue === 6 ? null : btnActiveValue,
            department: visible.value,
            ticket_title: store.searchName || ''
        }

        getWorkOrderList(params).then((res: any) => {

            resolve({
                ...res,
                data: res.data
            })
        }).catch((err) => {
            reject(err)
        });
    })
}

//获取上拉下拉数据
const requestData = (pageIndex: number, pageSize: number) => {
    return requestItems(active.value, btnActive.value, pageIndex, pageSize)
}

// 获取工单列表
const tabClick = () => {
    if (listRef.value) {
        listRef.value.$el.scrollTop = 0
        listRef.value?.dataInitialization()
    }
}

// 跳转详情
const goDetail = (id: number) => {
    router.push({ path: '/work-order-detail', query: { id: id } })
}

const createWorkOrder = () => {
    router.push('/create-new-work-order')
}

// 检测设备类型和浏览器，设置底部间距
const adjustBottomPadding = () => {
    const cardList = document.querySelector('.card-list') as HTMLElement
    if (!cardList) return

    const userAgent = navigator.userAgent.toLowerCase()
    const isAndroid = /android/.test(userAgent)
    const isEdge = /edg/.test(userAgent)
    const isSafari = /safari/.test(userAgent) && !/chrome/.test(userAgent)

    if (isAndroid && isEdge) {
        cardList.style.paddingBottom = '110px'
    }

    // Safari浏览器特别处理
    if (isSafari) {
        cardList.style.paddingBottom = '110px'

        // 延迟再次强制显示创建工单按钮
        setTimeout(() => {
            const btnContainer = document.querySelector('.add-work-order-container') as HTMLElement
            const addWorkOrder = document.querySelector('.add-work-order') as HTMLElement

            if (btnContainer) {
                btnContainer.style.display = 'flex'
                btnContainer.style.visibility = 'visible'
                btnContainer.style.opacity = '1'
            }

            if (addWorkOrder) {
                addWorkOrder.style.display = 'flex'
                addWorkOrder.style.visibility = 'visible'
                addWorkOrder.style.opacity = '1'
            }
        }, 300)
    }
}

//工单搜索
watch(() => store.searchName, () => {
    listRef.value?.dataInitialization()
})

</script>

<style lang="scss" scoped>
.work-order {
    padding: 10px;
    box-sizing: border-box;
    position: relative;
    height: 100vh;
    overflow: hidden;
    background: #fff;

    :deep(.van-tabs) {

        .van-tabs__wrap {

            .van-tabs__nav--line {
                height: 20px;
            }

            .van-tabs__nav {

                .van-tabs__line {
                    background: #000;
                    height: 2px;
                    bottom: 10px;
                }
            }
        }
    }

    .work-order-btn {
        :deep(.van-tabs) {

            .van-tabs__wrap {
                height: 30px;

                .van-tabs__nav--complete {
                    padding-left: 0;
                }

                .van-tabs__nav {

                    .van-tab--grow {
                        padding: 0 10px 0 0;
                        font-size: 11.5px;
                    }

                    .van-tabs__line {
                        width: 25px;
                        height: 2px;
                        left: -5px;
                        bottom: 13px;

                    }
                }
            }
        }
    }

    .card-list {
        height: calc(100vh - 175px);
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        padding: 10px;
        padding-bottom: 80px;
        box-sizing: border-box;
        position: relative;

        .card-item {
            padding: 15px;
            width: 100%;
            background: #eee;
            box-sizing: border-box;
            margin-bottom: 10px;
            border-radius: 10px;
        }
    }

    // iOS设备
    @supports (-webkit-touch-callout: none) {
        .card-list {
            padding-bottom: 80px;
            height: calc(100vh - 175px - env(safe-area-inset-bottom));
        }

        //安卓Edge浏览器
        @media screen and (-webkit-min-device-pixel-ratio:0) and (not (-webkit-touch-callout: none)) {
            .card-list {
                padding-bottom: 160px;
            }
        }

        // Safari特定样式
        :global(.safari-browser) {
            .add-work-order-container {
                display: flex !important;
                visibility: visible !important;
                opacity: 1 !important;
                z-index: 10000 !important;
            }

            .add-work-order {
                display: flex !important;
                visibility: visible !important;
                opacity: 1 !important;
            }
        }
    }
}
</style>